using Sirenix.OdinInspector;
using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

namespace Custom.Daily.Toolkit
{
    public enum ScreenShotPhotoGraph
    {
        [LabelText("3D拍照")]
        Photo3D,
        [LabelText("截取全屏UI")]
        FullScreenUI,
        [LabelText("截取局部UI")]
        PartialScreenUI
    }

    [AddComponentMenu("拍照截图")]
    public class ScreenShot : MonoBehaviour
    {
        [SerializeField, LabelText("模式")]
        public ScreenShotPhotoGraph model;
        [LabelText("局部截图UI对象"), ShowIf("model", ScreenShotPhotoGraph.PartialScreenUI)]
        public RectTransform uiRect;
        [LabelText("3D拍照相机"), ShowIf("model", ScreenShotPhotoGraph.Photo3D)]
        public Camera cam;
        [LabelText("图片保存地址(路径+名称.png)")]
        public string address;
        [LabelText("成功后的回调方法")] 
        public UnityEvent callback;

        #region 外部接口
        /// <summary>
        /// 拍照截屏
        /// </summary>
        [Button("Invoke", ButtonHeight = 30)]
        public void StartScreenShot()
        {
            switch (model)
            {
                case ScreenShotPhotoGraph.Photo3D:
                    StartCoroutine(CaptureCamera());
                    break;
                case ScreenShotPhotoGraph.FullScreenUI:
                    StartCoroutine(FullScreenShot());
                    break;
                case ScreenShotPhotoGraph.PartialScreenUI:
                    CutPartScreen();
                    break;
            }
        }
        # endregion

        // 拍照
        private IEnumerator CaptureCamera()
        {
            //等待帧画面渲染结束
            yield return new WaitForEndOfFrame();
            try
            {
                var viewportRect = cam.rect;
                var screenWidth = Screen.width;
                var screenHeight = Screen.height;
                var width = (int)(viewportRect.width * screenWidth);
                var height = (int)(viewportRect.height * screenHeight);

                // 保存相机原始的 targetTexture
                var originalTargetTexture = cam.targetTexture;

                // 使用相机视口大小创建 RenderTexture
                var renderTexture = new RenderTexture(width, height, 24); // 使用 24 位深度缓冲区
                cam.targetTexture = renderTexture;

                // 渲染相机画面到 RenderTexture
                cam.Render();

                // 激活 RenderTexture 并读取像素数据
                RenderTexture.active = renderTexture;
                var screenShot = new Texture2D(width, height, TextureFormat.RGB24, false);
                // 只读取相机视口的区域
                screenShot.ReadPixels(new Rect(0, 0, width, height), 0, 0);
                screenShot.Apply();

                // 恢复相机原始的 targetTexture
                cam.targetTexture = originalTargetTexture;
                RenderTexture.active = null;
                
                var bytes = screenShot.EncodeToPNG();
                File.WriteAllBytes(address, bytes);
                callback?.Invoke();
            }
            catch (Exception e)
            {
                Debug.LogWarning($"拍照失败,address:{address}.报错:{e.Message}");
            }
        }

        // 截全屏
        private IEnumerator FullScreenShot()
        {
            //等待帧画面渲染结束
            yield return new WaitForEndOfFrame();
            try
            {
                ScreenCapture.CaptureScreenshot(address);
                callback?.Invoke();
            }catch(Exception e)
            {
                Debug.LogWarning($"全屏截取失败,address:{address}.报错:{e.Message}");
            }
        }

        // 截局部
        private void CutPartScreen()
        {
            //系统不识别标点符号，但支持中文
            StartCoroutine(CaptureByUI(uiRect, address));
        }
        private IEnumerator CaptureByUI(RectTransform UIRect, string mFileName)
        {
            //等待帧画面渲染结束
            yield return new WaitForEndOfFrame();
            try
            {
                var uiRectRect = UIRect.rect;

                var width = (int)(uiRectRect.width);
                var height = (int)(uiRectRect.height);
                var tex = new Texture2D(width, height, TextureFormat.RGB24, false);

                //左下角为原点（0, 0）
                var vector3 = UIRect.transform.position;
                var leftBtmX = vector3.x + uiRectRect.xMin;
                var leftBtmY = vector3.y + uiRectRect.yMin;

                //从屏幕读取像素, leftBtmX/leftBtnY 是读取的初始位置,width、height是读取像素的宽度和高度
                tex.ReadPixels(new Rect(leftBtmX, leftBtmY, width, height), 0, 0);
                //执行读取操作
                tex.Apply();
                var bytes = tex.EncodeToPNG();
                //保存
                File.WriteAllBytes(mFileName, bytes);
                callback?.Invoke();
            }
            catch (Exception e)
            {
                Debug.LogWarning($"局部截屏失败,address:{mFileName}.报错:{e.Message}");
            }
        }
    }
}
